// 路径：src/main/java/electricity/util/AliOssUtil.java
package electricity.Utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.OSSObjectSummary;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Component
public class AliOssUtil {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;  // 现在可以正常使用 bucketName 了



    // 获取 OSS 客户端
    private OSS getOssClient() {
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 获取 OSS 所有文件路径（修复 listObjects 方法）
     */
    public List<String> listAllObjectPaths(String bucketName) {
        OSS ossClient = getOssClient();
        List<String> allPaths = new ArrayList<>();
        String marker = null;

        try {
            do {
                // 使用 ListObjectsRequest 构建请求（适配新版 SDK）
                ListObjectsRequest request = new ListObjectsRequest(bucketName)
                        .withPrefix("") // 前缀（空表示所有文件）
                        .withMarker(marker) // 分页标记
                        .withMaxKeys(1000); // 每页最大数量

                ObjectListing listing = ossClient.listObjects(request);
                for (OSSObjectSummary summary : listing.getObjectSummaries()) {
                    allPaths.add(summary.getKey());
                }
                marker = listing.getNextMarker();
            } while (marker != null);
        } finally {
            ossClient.shutdown();
        }
        return allPaths;
    }

    /**
     * 获取指定目录下的文件列表（修复 listObjects 方法）
     */
    public List<OssFile> listFilesInDirectory(String bucketName, String directory) {
        OSS ossClient = getOssClient();
        List<OssFile> files = new ArrayList<>();
        String marker = null;

        try {
            do {
                // 构建目录查询请求
                ListObjectsRequest request = new ListObjectsRequest(bucketName)
                        .withPrefix(directory + "/") // 目录前缀
                        .withMarker(marker)
                        .withMaxKeys(1000);

                ObjectListing listing = ossClient.listObjects(request);
                for (OSSObjectSummary summary : listing.getObjectSummaries()) {
                    String fullPath = summary.getKey();
                    String fileName = fullPath.substring(directory.length() + 1);
                    files.add(new OssFile(fileName, fullPath, summary.getSize()));
                }
                marker = listing.getNextMarker();
            } while (marker != null);
        } finally {
            ossClient.shutdown();
        }
        return files;
    }

    /**
     * 上传文件（不变）
     */
    public String uploadFile(InputStream inputStream, String bucketName, String directory, String fileName) throws IOException {
        String objectName = directory + "/" + fileName;
        OSS ossClient = getOssClient();

        try {
            ossClient.putObject(bucketName, objectName, inputStream);
            return "https://" + bucketName + "." + endpoint.replace("https://", "") + "/" + objectName;
        } finally {
            ossClient.shutdown();
            inputStream.close();
        }
    }


    public InputStream download(String objectName) {
        OSS ossClient = getOssClient();
        try {
            return ossClient.getObject(bucketName, objectName).getObjectContent();
        } finally {
            ossClient.shutdown();
        }
    }

    /**
     * 删除文件（可选）
     */
    public void deleteFile(String objectName) {
        OSS ossClient = getOssClient();
        try {
            ossClient.deleteObject(bucketName, objectName);
        } finally {
            ossClient.shutdown();
        }
    }
    // 封装文件信息（不变）
    public static class OssFile {
        private String name;
        private String path;
        private long size;

        public OssFile(String name, String path, long size) {
            this.name = name;
            this.path = path;
            this.size = size;
        }

        public String getName() { return name; }
        public String getPath() { return path; }
        public long getSize() { return size; }
    }
}
